/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.data;

import java.util.HashMap;
import java.util.Map;

/**
 * An instance of {@link FieldBaseStructureDefinition}
 */
public class FieldBaseStructureInstance implements StructureInstance {

    protected FieldBaseStructureDefinition structureDefinition;

    protected Map<String, Object> fieldValues;

    public FieldBaseStructureInstance(FieldBaseStructureDefinition structureDefinition) {
        this.structureDefinition = structureDefinition;
        this.fieldValues = new HashMap<String, Object>();
    }

    public Object getFieldValue(String fieldName) {
        return this.fieldValues.get(fieldName);
    }

    public void setFieldValue(String fieldName, Object value) {
        this.fieldValues.put(fieldName, value);
    }

    public int getFieldSize() {
        return this.structureDefinition.getFieldSize();
    }

    public String getFieldNameAt(int index) {
        return this.structureDefinition.getFieldNameAt(index);
    }

    @Override
    public Object[] toArray() {
        int fieldSize = this.getFieldSize();
        Object[] arguments = new Object[fieldSize];
        for (int i = 0; i < fieldSize; i++) {
            String fieldName = this.getFieldNameAt(i);
            Object argument = this.getFieldValue(fieldName);
            arguments[i] = argument;
        }
        return arguments;
    }

    @Override
    public void loadFrom(Object[] array) {
        int fieldSize = this.getFieldSize();
        for (int i = 0; i < fieldSize; i++) {
            String fieldName = this.getFieldNameAt(i);
            Object fieldValue = array[i];
            this.setFieldValue(fieldName, fieldValue);
        }
    }
}
